import { defineStore } from 'pinia'
import { useUserStore } from './user'
import { computed, ref } from 'vue'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  // 1. 定义state - cartList
  const cartList = ref([])
  // 2. 定义action - addCart
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      // 登录之后的加入购车逻辑
      await insertCartAPI({ skuId, count })
      updateNewList()
    } else {
      // 添加购物车操作
      // 已添加过 - count + 1
      // 没有添加过 - 直接push
      // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        // 找到了
        item.count++
      } else {
        // 没找到
        cartList.value.push(goods)
      }
    }

  }
  // 3. 定义action - delCart
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      updateNewList()
    }else{
      const index = cartList.value.findIndex((item) => item.skuId === skuId)
      cartList.value.splice(index, 1)
    }
  }

  // 4. 更新最新的购物车列表
  const updateNewList = async ()=>{
    const res = await findNewCartListAPI()
      cartList.value = res.data.result
  }

  // 5. 清除购物车
  const clearCart = ()=>{
    cartList.value = []
  }

  const allCount = computed(() => cartList.value.reduce((result, item) => result + item.count, 0))

  const allPrice = computed(() => cartList.value.reduce((result, item) => result + item.count * item.price, 0))

  const selectedCount = computed(() => cartList.value.filter(i => i.selected).reduce((result, item) => result + item.count, 0))

  const selectedPrice = computed(() => cartList.value.filter(i => i.selected).reduce((result, item) => result + item.count * item.price, 0))


  // 单选功能
  const singleCheck = (skuId, selected) => {
    // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }
  // 全选
  const isAll = computed(() => {
    return cartList.value.every(item => item.selected)
  })

  const checkAll = (selected) => {
    cartList.value.forEach(item => {
      item.selected = selected
    })
  }

  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    isAll,
    checkAll,
    selectedCount,
    selectedPrice,
    clearCart,
    updateNewList
  }
}, {
  persist: true,
})